package vip.meeet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

public class ESUtil {

    private static final String HTTP = "http";

    private static String NODE_A = "127.0.0.1";

    private static Integer CLUSTER_PORT = 9200;


    public static RestHighLevelClient getClient(){
        HttpHost httpHost = new HttpHost(NODE_A, CLUSTER_PORT, HTTP);
        RestClientBuilder builder = RestClient.builder(httpHost);
        return new RestHighLevelClient(builder);
    }

    /**
     * https://www.elastic.co/guide/en/elasticsearch/reference/7.1/search-request-scroll.html
     * @param scrollId
     * @param time
     * @return
     */
    public static String scrollRequestBody(String scrollId,String time){
        JSONObject result = new JSONObject();
        result.put("scroll_id",scrollId);
        result.put("scroll",time);
        return result.toJSONString();
    }

    public static String queryMatchAll(){
        JSONObject matchAll = new JSONObject();
        matchAll.put("match_all",new JSONObject());
        JSONObject query = new JSONObject();
        query.put("query",matchAll);
        return query.toJSONString();
    }

    public static String scrollFirst(int size){
        return scrollFirst(null,size);
    }

    public static String scrollFirst(String time, int size){
        JSONObject matchAll = new JSONObject();
        matchAll.put("match_all",new JSONObject());
        JSONObject srollRequest = new JSONObject();
        srollRequest.put("query",matchAll);
        srollRequest.put("size",size);
        JSONArray sorted = new JSONArray();
        sorted.add("_doc");
        srollRequest.put("sort",sorted);
        if(time != null) {
            srollRequest.put("scroll", time);
        }
        return srollRequest.toJSONString();
    }
}
